package biolabs.gui;

import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

/**
 * Loader is a fixed-size component that displays
 * an indication that some operation is in progress.
 *
 * @author Tomas Mikula
 */
class Loader extends JLabel {

	private static final long serialVersionUID = 1L;

	/**
	 * Animated icon indicating an operation in progress.
	 */
	private static final ImageIcon LOADER_ICON =
			new ImageIcon(Stage.class.getResource("loader.gif"));

	/**
	 * Transparent icon of the same size as {@link #LOADER_ICON}.
	 */
	private static final Icon LOADER_PLACEHOLDER = new Icon() {
		@Override
		public int getIconHeight() {
			return LOADER_ICON.getIconHeight();
		}
		@Override
		public int getIconWidth() {
			return LOADER_ICON.getIconWidth();
		}
		@Override
		public void paintIcon(Component c, Graphics g, int x, int y) {
			g.clearRect(x, y, getIconWidth(), getIconHeight());
		}
	};

	/**
	 * Creates a loader. The loader is OFF upon creation.
	 */
	public Loader() {
		super(Loader.LOADER_PLACEHOLDER);
	}

	/**
	 * Displays the loading animation.
	 */
	public void on() {
		setIcon(LOADER_ICON);
	}

	/**
	 * Hides the loading animation
	 * (the icon area is filled with background color).
	 */
	public void off() {
		setIcon(LOADER_PLACEHOLDER);
	}

	/**
	 * Returns {@code true} if this loader is currently
	 * displaying the loading animation, {@code false} otherwise.
	 */
	public boolean isOn() {
		return getIcon() == LOADER_ICON;
	}
}
